import React, {memo, useEffect, useState} from 'react'
import {BrowserRouter} from 'react-router-dom'
import ErrorModal from './error/ErrorModal'
import {ToastContainer} from '../../ui/toast/ToastContainer'
import NotFoundPage from './notFound/NotFoundPage'
import ReduxApp from '../../store/ReduxApp'
import {apiPost} from '../../api'
import {CONSTANTS} from '../../../constants'
import {ACTION_TYPES} from '../../store/action/ActionTypes'
import {LSMethods} from '../../storage'
import {KEYS} from '../../storage/keys'
import {IResponse} from '../../api/IResponse'
import {UserDto} from '../../../api/UserDto'
import {CartDto} from '../../../api/CartDto'

interface Props {
  store: any
  urlPrefix?: string
  locationSSR?: string
  isServer?: boolean
}

const App: React.FC<Props> = memo(
  ({store, urlPrefix, isServer, locationSSR, children}): React.ReactElement => {
    const [isInitialized, setIsInitialized] = useState<boolean>(true)

    useEffect(() => {
      loadData()
    }, [])

    const loadData = async (): Promise<void> => {
      const token: any = LSMethods.getStorageData(KEYS.TOKEN) //TODO:: TokenDto
      if (token) {
        let user: UserDto
        let cart: CartDto
        try {
          const resCheck: IResponse = await apiPost(
            CONSTANTS.apiUrl + '/auth/check',
            {token: token},
            {},
          )
          user = resCheck.result
          const resCart: IResponse = await apiPost(
            CONSTANTS.apiUrl + '/cart/read',
            {token: token},
            {},
          )
          cart = {
            dishes: resCart.result?.dishes || [],
            id: resCart.result?.id || null,
          }
        } catch (err: any) {
          if (err.status === 401) {
            LSMethods.removeItem(KEYS.TOKEN)
          } else {
            console.log('LoadData app', err)
          }
        }
        store.dispatch({type: ACTION_TYPES.AUTH_SET_STATE, state: {user, cart}})
      }
      setIsInitialized(true)
    }

    const renderContent = () => {
      if (isInitialized) {
        const pathname: string = window.location.pathname
        return (
          <BrowserRouter basename={urlPrefix}>
            <div className={'height-100vh'}>
              <ErrorModal />
              <ToastContainer />
              <div className={'height-100vh'}>
                {pathname === '/404' || pathname === (urlPrefix || '') + '/404' ? (
                  <NotFoundPage />
                ) : (
                  <>{children}</>
                )}
              </div>
            </div>
          </BrowserRouter>
        )
      } else {
        return null
      }
    }

    return <ReduxApp store={store}>{renderContent()}</ReduxApp>
  },
)
export default App
